<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}配送员`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="userInfo"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="配送员头像" prop="avatar">
        <UploadImg v-model:image-url="userInfo.userAvatar" width="135px" height="135px" :file-size="3">
          <template #empty>
            <el-icon><Avatar /></el-icon>
            <span>请上传头像</span>
          </template>
          <template #tip> 头像大小不能超过 3M </template>
        </UploadImg>
      </el-form-item>
      <el-form-item label="头像选择">
        <el-button @click="changeAvatar" type="primary">随机头像</el-button>
      </el-form-item>
      <p></p>
      <el-form-item label="配送员账号" prop="username">
        <el-input v-model="userInfo.username" placeholder="请填写配送员账号" clearable></el-input>
      </el-form-item>
      <el-form-item label="配送员姓名" prop="name">
        <el-input v-model="userInfo.name" placeholder="请填写配送员姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="userGender">
        <el-select v-model="userInfo.userGender" placeholder="请选择性别" clearable>
          <el-option v-for="item in genderType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="身份证号" prop="userIdentity">
        <el-input v-model="userInfo.userIdentity" placeholder="请填写身份证号" clearable></el-input>
      </el-form-item>
      <el-form-item label="电话号" prop="userPhone">
        <el-input v-model="userInfo.userPhone" placeholder="请填写电话号" clearable></el-input>
      </el-form-item>
      <el-form-item label="身份" prop="userRole">
        <el-select v-model="userInfo.userRole" readonly clearable>
          <el-option :key="8" label="配送员" :value="8" />
        </el-select>
      </el-form-item>
      <el-form-item label="分站编号" prop="departmentId">
        <el-input v-model="userInfo.departmentId" placeholder="请选择部门" readonly></el-input>
      </el-form-item>
      <el-form-item label="分站名称" prop="departmentName">
        <el-input v-model="userInfo.departmentName" placeholder="请选择部门" readonly></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button @click="newUser">随机生成</el-button>
      <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive } from "vue";
import { genderType } from "@/utils/serviceDict";
import { ElMessage, FormInstance } from "element-plus";
import { User } from "@/api/interface";
import UploadImg from "@/components/Upload/Img.vue";
import { useUserStore } from "@/stores/modules/user";
import { imageLinks } from "@/utils/avatarLinks";
const userStore = useUserStore();

interface DrawerProps {
  title: string;
  isView: boolean;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: ""
});
// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

const userInfo = ref<Partial<User.UserEntity>>({
  userStatus: 0,
  userRole: 8,
  departmentId: userStore.userInfo.departmentId,
  departmentName: userStore.userInfo.departmentName,
  userAvatar: imageLinks[Math.floor(Math.random() * imageLinks.length)]
});

const rules = reactive({
  name: [
    { required: true, message: "请填写配送员姓名" },
    { pattern: /^[\u4e00-\u9fa5]{2,4}$/, message: "姓名格式不正确" }
  ],
  userGender: [{ required: true, message: "请选择性别" }],
  username: [
    { required: true, message: "请填写配送员账号" },
    { min: 4, max: 20, message: "账号长度为4到20个字符" }
  ],
  userIdentity: [
    { required: true, message: "请填写身份证号" },
    { pattern: /^\d{17}[\dXx]$/, message: "身份证号格式不正确" }
  ],
  userRole: [{ required: true, message: "请选择配送员身份" }],
  userPhone: [
    { required: true, message: "请填写电话号" },
    { pattern: /^1[3-9]\d{9}$/, message: "电话号格式不正确" }
  ],
  departmentId: [{ required: true, message: "请选择部门" }],
  departmentName: [{ required: true, message: "请选择部门" }]
});

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    // if (!showDepartment.value) {
    //   // 非分站和库房的配送员，部门id等于role,部门名称等于标签值
    //   userInfo.value.departmentId = userInfo.value.userRole;
    //   userInfo.value.departmentName = findLabelByValue(userInfo.value.userRole);
    // }
    if (!valid) return;
    // if (userInfo.value.departmentId == undefined || userInfo.value.departmentName == undefined) {
    //   ElMessage.error({ message: `请选择部门！` });
    //   return;
    // }
    try {
      await drawerProps.value.api!(userInfo.value);
      ElMessage.success({ message: `${drawerProps.value.title}配送员成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

const changeAvatar = () => {
  //随机选取一个头像
  userInfo.value.userAvatar = imageLinks[Math.floor(Math.random() * imageLinks.length)];
};

const newUser = () => {
  //随机选取一个头像
  userInfo.value.userAvatar = imageLinks[Math.floor(Math.random() * imageLinks.length)];
  userInfo.value.username = "12349865";
  userInfo.value.name = "力咖啡";
  userInfo.value.userGender = 1;
  userInfo.value.userIdentity = "140109200207054517";
  userInfo.value.userPhone = "15333008409";
};

defineExpose({
  acceptParams
});
</script>
